package com.lwx.chapter11;

/**
 * Quick Find
 * 并 O(n)
 * 查 O(1)
 */
public class UnionFind1 implements UF {
    //元素所在的集合编号
    private int[] id;

    public UnionFind1(int size) {
        id = new int[size];
        for (int i = 0; i < size; i++) {
            id[i] = i;
        }
    }

    @Override
    public int getSize() {
        return id.length;
    }

    //查找元素p所对应的集合编号
    private int find(int p){
        if(p < 0 || p >= id.length){
            throw new IllegalArgumentException("p is out of bound.");
        }
        return id[p];
    }

    // 查看p,q是否属于同一个元素
    // O(1)
    @Override
    public boolean isConnected(int p, int q) {
        return find(p) == find(q);
    }

    //将q所在的集合，合并到p所在的集合
    //O(n)
    @Override
    public void unionElements(int p, int q) {
        // p 所在的集合
        int pId = find(p);
        int qId = find(q);

        if(pId == qId){
            return;
        }

        for (int i = 0; i < id.length; i++) {
            if(find(i) == qId){
                id[i] = pId;
            }
        }
    }
}
